<?php
namespace app\index\model;
use app\common\model\StoreUser as StoreUserModel;
use app\common\model\WebSet as WebSetModel;
use think\Session;

/**
 * 商家用户模型
 */
class StoreUser extends StoreUserModel
{
	/**
     * 添加
     
    public function add(array $data)
    {
		//验证手机号是否合法
		if(!isMobile($data['user_name'])){
			$this->error = '手机号码不合法';
            return false;
		}
		//验证账号是否存在
		if(StoreUserModel::detail($data['user_name'])){
			$this->error = '该账号已存在';
            return false;
		}
		//验证密码长度是否合法
		if(strlen($data['password'])<6){
			$this->error = '密码长度不足6位';
            return false;
		}
		//验证两次密码是否一致
		if($data['password']!==$data['password2']){
			$this->error = '两次密码不一致';
            return false;
		}
		//获取初始用户配置
		$values = WebSetModel::getItem('user');
		switch($values['term_unit']){
			case 10:
				$data['expire_time'] = strtotime('+'.$values['term'].'day');
				break;
			case 20:
				$data['expire_time'] = strtotime('+'.$values['term'].'week');
				break;
			case 30:
				$data['expire_time'] = strtotime('+'.$values['term'].'month');
				break;
			case 40:
				$data['expire_time'] = strtotime('+'.$values['term'].'year');
				break;
			default:
				$data['expire_time'] = time();	
		}
		$data['password'] = hema_hash($data['password']);
        // 添加
        return $this->allowField(true)->save($data);
    }
*/
    /**
     * 商家用户登录
     */
    public function login($data)
    {
		$filter = [
            'user_name' => $data['user_name'],
            'password' => hema_hash($data['password'])
        ];
        // 验证用户名密码是否正确
		if($user = $this->useGlobalScope(false)->where($filter)->find()){
			// 保存登录状态
			Session::set('hema_store', [
				'user' => [
					'store_user_id' => $user['store_user_id'],
					'user_name' => $user['user_name']
				],
				'is_login' => true,
			]);
			return true;
		}else{
			$this->error = '登录失败, 用户名或密码错误';
            return false;
		}
    }  

    /**
     * 修改管理员密码
     */
    public function renew($data)
    {
        //验证密码长度是否合法
		if(strlen($data['password'])<6){
			$this->error = '密码长度不足6位';
            return false;
		}
		if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        // 更新管理员信息
        if ($this->save([
                'password' => hema_hash($data['password']),
				'phone' => $data['phone'],
				'linkman' => $data['linkman']
            ]) === false) {
            return false;
        }
        return true;
    }

}
